package cn.com.callback

import cn.com.kh.KHUtil
import com.alibaba.fastjson.JSONObject
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.com.callback.ServiceBackInvoke
import cn.com.elite.EliteBean

import java.text.SimpleDateFormat;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory
import com.huasheng.passwordencrypt.DecryptUtil

/**
 *
 * @Title: aipHSTImportEsopCustomer
 * @Description:华盛证券 Esop 导入的客户数据更新 --内部接口
 * @author: chieh
 * @date 2023-10-13 11:45:00
 *
 */

public class aipHSTImportEsopCustomer implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(aipHSTImportEsopCustomer.class);

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {
        response.setCharacterEncoding("UTF-8");

        String getMethod = request.getMethod();

        log.debug("getMethod:" + getMethod);
        long endTime;
        String inData = "";
        String outData = "";
        String dataSourceID = "dataSource";

        BufferedReader iny = null;
        if (getMethod.equals("GET")) {
            inData = request.getParameter("data");
            log.debug("原始Get请求参数:" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
            iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("原始Post请求参数:" + inData);
        }

        try {
            long startTime = System.currentTimeMillis();

            // 调用处理信息
            JSONObject inObject = JSONObject.parseObject(inData);
            log.debug("处理前的Json：" + inObject.toString());
            def batchid = inObject.getString("batchid");//批次id
            def type = inObject.getString("type");//导入类别（add 新增 update 覆盖）

            log.debug("解析信息-" + "batchid: " + batchid);
            if (batchid != '' && batchid != null) {
                outData = allocationData(eliteBean, batchid, type, inObject, dataSourceID);
            } else {
                log.error("处理失败(批次号为空错误)!");
                endTime = System.currentTimeMillis();
                return "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(批次号为空错误),调用问题处理时长(毫秒):" + (endTime - startTime) + "\",\"data\":[]}";
            }

        } catch (Exception e) {
            log.error("接口处理异常" + e.getMessage());
            outData = "{\"resultcode\":\"0\",\"resultmessage\":\"处理失败(" + e.getMessage() + ")\",\"data\":[]}";
        }

        log.debug("完成返回结果:" + outData);

        return outData;
    }

    // 处理Esop客户信息
    public static String allocationData(EliteBean eliteBean, String batchid, String type, JSONObject inObject, String dataSourceID) {

        long startTime = System.currentTimeMillis();
        long endTime = System.currentTimeMillis();
        JSONObject resultJson = new JSONObject();
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        log.debug("startTime" + startTime);

        try {

            //循环捞取当前批次的任务
            def selectesopcustomerSQL = "select DISTINCT CUSTOMERNAME,CUSTOMER_ID,GENDER,MOBILE,E_MAIL,OPEN_ID,area_id,STRINGFIELD108,guid from  hst_esop_customer_details where batch_id='" + batchid + "' and CUSTOMER_ID is not null and CUSTOMER_ID!=''";

            log.debug("查询数量selectesopcustomerSQL=" + selectesopcustomerSQL);
            List selectesopcustomeraryList = eliteBean.chaxun_sql(selectesopcustomerSQL, "dataSource");

            def ListNum = selectesopcustomeraryList.size();
            log.debug("待分配ListNum=" + ListNum);

            String[] insertSQL = new String[ListNum];
            String[] updateSQL = new String[ListNum];
            int m = 0;
            int n = 0;
            int arrInt = 100;
            //轮询分配次数
            double number = ListNum * 1.0 / arrInt;
            log.debug("轮询分配次数number :" + number);
            //轮询次数向上取整
            int count = Math.ceil(number);
            log.debug("轮询次数取整count :" + count);
            int yscount = ListNum % arrInt;
            log.debug("yscount :" + yscount);
            String MOBILE_enc,E_MAIL_enc,OPEN_ID_enc="";
            for (int j = 0; j < ListNum; j++) {
                String guid = selectesopcustomeraryList.get(j).get("guid");  //主键
                String CUSTOMERNAME = selectesopcustomeraryList.get(j).get("CUSTOMERNAME");  //客户名称
                String CUSTOMER_ID = selectesopcustomeraryList.get(j).get("CUSTOMER_ID");  //客户ID 唯一
                String GENDER = selectesopcustomeraryList.get(j).get("GENDER");  //性别
                String MOBILE = selectesopcustomeraryList.get(j).get("MOBILE");  //电话方式
                String E_MAIL = selectesopcustomeraryList.get(j).get("E_MAIL");  //邮箱
                String OPEN_ID = selectesopcustomeraryList.get(j).get("OPEN_ID");  //WhatsApp账号信息
                String area_id = selectesopcustomeraryList.get(j).get("area_id");  //区号
                String STRINGFIELD108 = selectesopcustomeraryList.get(j).get("STRINGFIELD108");  //所属公司
                MOBILE_enc = DecryptUtil.encrypt(MOBILE) ;
                E_MAIL_enc = DecryptUtil.encrypt(E_MAIL) ;
                OPEN_ID_enc = DecryptUtil.encrypt(OPEN_ID) ;
                log.debug("MOBILE_enc:"+MOBILE_enc+"  E_MAIL_enc:"+E_MAIL_enc+" OPEN_ID_enc:"+OPEN_ID_enc);

                def getobjecitiveSelectSQL = eliteBean.chaxun_sql("select  customer_guid  from customer where  customer_id='" + CUSTOMER_ID + "' and stringfield105='Esop'", "dataSource")
                if (getobjecitiveSelectSQL.size() > 0) {
                    log.debug("已存在！");
                    if(type=="add"){//仅新增
                        insertSQL[j]=null;
                        updateSQL[j]="update hst_esop_customer_details set state='2',statedesc='客户已存在！' where guid='" + guid + "'";
                    }else if(type=="update"){//覆盖更新
                        insertSQL[j]="update customer set CUSTOMERNAME=case when '" + CUSTOMERNAME + "' is null or '" + CUSTOMERNAME + "'='' then Customername else '" + CUSTOMERNAME + "' end, GENDER=case when '" + GENDER + "' is null or '" + GENDER + "'='' then GENDER else '" + GENDER + "' end, MOBILE='***', E_MAIL='***', OPEN_ID='" + OPEN_ID + "', area_id=case when '" + area_id + "' is null or '" + area_id + "'='' then area_id else '" + area_id + "' end, STRINGFIELD108=case when '" + STRINGFIELD108 + "' is null or '" + STRINGFIELD108 + "'='' then STRINGFIELD108 else '" + STRINGFIELD108 + "' end,MOBILE_enc=case when '" + MOBILE_enc + "' is null or '" + MOBILE_enc + "'='' then MOBILE_enc else '" + MOBILE_enc + "' end,E_MAIL_enc=case when '" + E_MAIL_enc + "' is null or '" + E_MAIL_enc + "'='' then E_MAIL_enc else '" + E_MAIL_enc + "' end,OPEN_ID_enc=case when '" + OPEN_ID_enc + "' is null or '" + OPEN_ID_enc + "'='' then OPEN_ID_enc else '" + OPEN_ID_enc + "' end where CUSTOMER_ID='" + CUSTOMER_ID + "'";
                        updateSQL[j]="update hst_esop_customer_details set state='1',statedesc='客户已存在，覆盖更新成功！' where guid='" + guid + "'";
                    }

                }else{
                    log.debug("不存在新增！");
                    insertSQL[j] = "insert into customer (customer_guid,CUSTOMERNAME,CUSTOMER_ID,GENDER,MOBILE,E_MAIL,OPEN_ID,stringfield9,stringfield105,area_id,STRINGFIELD108,MOBILE_enc,E_MAIL_enc,OPEN_ID_enc,CREATEDBY,CREATEDDATE) values(UUID(),'" + CUSTOMERNAME + "','" + CUSTOMER_ID + "','" + GENDER + "','***','***','" + OPEN_ID + "','" + CUSTOMER_ID + "','Esop','" + area_id + "','" + STRINGFIELD108 + "','" + MOBILE_enc + "','" + E_MAIL_enc + "','" + OPEN_ID_enc + "','SELETE',now())";
                    updateSQL[j]="update hst_esop_customer_details set state='1',statedesc='导入成功' where guid='" + guid + "'";
                }
                    m++;
                log.debug("前：这是第"+n+"次数据=======第"+m+"");

                if (m == arrInt || (n == count - 1 && m == yscount)) {
                    log.debug("这是第"+n+"次数据");
                    log.debug(insertSQL.toString());
                    log.debug(updateSQL.toString());
                    //将数据插入数据库
                    int[] customerguidsqlResult = eliteBean.updateBatch(insertSQL, dataSourceID);
                    log.debug("customer提交数据库操作SQL结果:" + customerguidsqlResult.toString());
                    int[] detailssqlResult = eliteBean.updateBatch(updateSQL, dataSourceID);
                    log.debug("details提交数据库操作SQL结果:" + detailssqlResult.toString());
                    insertSQL = new String[ListNum];
                    updateSQL = new String[ListNum];
                    m = 0;
                    n++;
                }
            }
            //批量把为空为null的 更新 状态
            String updateCustSQL = "UPDATE hst_esop_customer_details set state='2',statedesc='必填项为空！'  WHERE batch_id='" + batchid + "'  and (CUSTOMER_ID is null or CUSTOMER_ID='')";
            def dataresult= eliteBean.update(updateCustSQL, "dataSource");

            // 生成处理完成时间
            endTime = System.currentTimeMillis();

            //将批次状态修改成已完成
            // 包装拼接返回JSONObject
            resultJson.put("resultcode", 1);
            resultJson.put("resultmessage", "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        } catch (Exception e) {
            endTime = System.currentTimeMillis();
            resultJson.put("resultcode", 4);
            resultJson.put("resultmessage", "处理失败:(" + e.getMessage() + ")" + "处理完成,调用问题处理时长(毫秒):" + (endTime - startTime));
        }

        return resultJson.toString();
    }

    // 解析Json值
    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
            } catch (Exception e1) {
                try {
                    Rev_Value = String.valueOf(inJson.getJSONArray(getKey));
                } catch (Exception e2) {
                    try {
                        Rev_Value = String.valueOf(inJson.getJSONObject(getKey));
                    } catch (Exception e3) {
                        Rev_Value = "";
                    }
                }
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                Rev_Value = "";
            } else {
            }
        }
        log.debug("解析-k=" + getKey + " v=" + Rev_Value);
        return Rev_Value;
    }

}
